package com.yeyks.rocketmq;

import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.PropertyValueConst;
import com.yeyks.common.constants.rocketmq.TopicAndTag;
import com.yeyks.rocketmq.listener.MessageGrabOrderListener;
import com.yeyks.rocketmq.listener.MessageGrabOrderResultListener;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * @author fuchangshuai
 * @date 2019/08/12 16:32
 */
@Data
@Slf4j
@Component
public class RocketMqConsumer {
    @Autowired
    private RocketMqConfig rocketMqConfig;

    /**
     * 抢单
     *
     * @return
     */
    @Bean(name = "messageGrabOrderConsumer")
    public Consumer getMessageGrabOrderConsumer(MessageGrabOrderListener messageGrabOrderListener) {
        log.info("初始化GrabOrder抢单启动消费者！");
        // producer 实例配置初始化
        Properties properties = rocketMqConfig.getProperties();
        // 集群订阅方式
        properties.setProperty(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
        properties.setProperty(PropertyKeyConst.GROUP_ID, TopicAndTag.GID_YYKSNORMAL_ROBTOBTAG);
        Consumer consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe(TopicAndTag.TOPIC_YYKS_NORMAL, TopicAndTag.TAG_ROB_TO_B_TAG, messageGrabOrderListener);
        consumer.start();
        log.info("启动GrabOrder抢单消费者成功！");
        return consumer;
    }

    /**
     * 抢单结果监听(包括下单通知)
     *
     * @return
     */
    @Bean(name = "messageGrabOrderResultConsumer")
    public Consumer getMessageGrabOrderResultConsumer(MessageGrabOrderResultListener messageGrabOrderResultListener) {
        log.info("初始化GrabOrderResult启动消费者！");
        Properties properties = rocketMqConfig.getProperties();
        properties.setProperty(PropertyKeyConst.GROUP_ID, TopicAndTag.GID_YYKSNORMAL_ROBRESULTTOBTAG);
        // 集群订阅方式
        properties.setProperty(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
        Consumer consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe(TopicAndTag.TOPIC_YYKS_NORMAL, TopicAndTag.TAG_ROB_RESULT_TO_B_TAG, messageGrabOrderResultListener);
        consumer.start();
        log.info("启动GrabOrderResult消费者成功！");
        return consumer;
    }
}
